package cn.wolfcode.web.modules.linkman.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.wolfcode.web.commons.entity.ExcelExportEntityWrapper;
import cn.wolfcode.web.commons.entity.LayuiPage;
import cn.wolfcode.web.commons.utils.LayuiTools;
import cn.wolfcode.web.commons.utils.PoiExportHelper;
import cn.wolfcode.web.commons.utils.PoiImportHelper;
import cn.wolfcode.web.commons.utils.SystemCheckUtils;
import cn.wolfcode.web.modules.BaseController;
import cn.wolfcode.web.modules.custinfo.entity.TbCustomer;
import cn.wolfcode.web.modules.custinfo.service.ITbCustomerService;
import cn.wolfcode.web.modules.log.LogModules;
import cn.wolfcode.web.modules.sys.entity.SysUser;
import cn.wolfcode.web.modules.sys.form.LoginForm;
import cn.wolfcode.web.modules.sys.service.SysUserService;
import cn.wolfcode.web.modules.visitinfo.entity.TbVisit;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
;

import cn.wolfcode.web.modules.linkman.entity.TbCustLinkman;
import cn.wolfcode.web.modules.linkman.service.ITbCustLinkmanService;


import link.ahsj.core.annotations.*;
import link.ahsj.core.entitys.ApiModel;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 叶师傅
 * @since 2024-06-02
 */
@Controller
@RequestMapping("linkman")
public class TbCustLinkmanController extends BaseController {

    @Autowired
    private ITbCustLinkmanService entityService;

    @Autowired
    private ITbCustomerService customerService;

    @Autowired
    private SysUserService sysUserService;

    private static final String LogModule = "TbCustLinkman";

    @GetMapping("/list.html")
    public ModelAndView list(ModelAndView mv) {

        //拿到企业列表
        List<TbCustomer> tbCustomerList = customerService.list();
        mv.addObject("tbCustomerList",tbCustomerList);
        mv.setViewName("user/linkman/list");
        return mv;
    }

    @RequestMapping("/add.html")
    @PreAuthorize("hasAuthority('user:linkman:add')")
    public ModelAndView toAdd(ModelAndView mv) {
        //拿到企业列表
        List<TbCustomer> tbCustomerList = customerService.list();
        mv.addObject("tbCustomerList",tbCustomerList);

        mv.setViewName("user/linkman/add");
        return mv;
    }

    @GetMapping("/{id}.html")
    @PreAuthorize("hasAuthority('user:linkman:update')")
    public ModelAndView toUpdate(@PathVariable("id") String id, ModelAndView mv) {
        //拿到企业列表
        List<TbCustomer> tbCustomerList = customerService.list();
        mv.addObject("tbCustomerList",tbCustomerList);

        mv.setViewName("user/linkman/update");
        mv.addObject("obj", entityService.getById(id));
        mv.addObject("id", id);
        return mv;
    }

    @RequestMapping("list")
    @PreAuthorize("hasAuthority('user:linkman:list')")
    public ResponseEntity page(LayuiPage layuiPage,String parameterName,String custId) {
        SystemCheckUtils.getInstance().checkMaxPage(layuiPage);
        IPage<TbCustLinkman> page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());

        page=entityService.lambdaQuery()
                .eq(!StringUtils.isEmpty(custId),TbCustLinkman::getCustId,custId) //所属企业
                .like(!StringUtils.isEmpty(parameterName),TbCustLinkman::getLinkman,parameterName)//联系人名字
                .or()
                .like(!StringUtils.isEmpty(parameterName),TbCustLinkman::getPhone,parameterName)//联系人手机

                .page(page);
        //分页列表
        List<TbCustLinkman> records = page.getRecords();
        for (TbCustLinkman custLinkman : records) {
            String custId1 = custLinkman.getCustId();
            //通过客户id查询对象
            TbCustomer tbCustomer = customerService.getById(custId1);
            if(tbCustomer!=null){
                //拿到客户名称赋值
                custLinkman.setCustName(tbCustomer.getCustomerName());

            }
            //显示录入人名字
            if(custLinkman.getInputUser()!=null){
                SysUser sysUser = sysUserService.getById(custLinkman.getInputUser());
                if (sysUser!=null){
                    custLinkman.setInputUserName(sysUser.getUsername());
                }
            }


        }

        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(page));
    }

    @SameUrlData
    @PostMapping("save")
    @SysLog(value = LogModules.SAVE, module =LogModule)
    @PreAuthorize("hasAuthority('user:linkman:add')")
    public ResponseEntity<ApiModel> save(@Validated({AddGroup.class})
                                             @RequestBody TbCustLinkman entity,
                                         HttpServletRequest request
    ) {
        //录入时间  获取的是当前时间
        entity.setInputTime(LocalDateTime.now());
        //录入人
        //从session中获取到用户信息
        SysUser sysUser = (SysUser)request.getSession().getAttribute(LoginForm.LOGIN_USER_KEY);
        //赋值用户id
        entity.setInputUser(sysUser.getUserId());

        entityService.save(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SameUrlData
    @SysLog(value = LogModules.UPDATE, module = LogModule)
    @PutMapping("update")
    @PreAuthorize("hasAuthority('user:linkman:update')")
    public ResponseEntity<ApiModel> update(@Validated({UpdateGroup.class}) @RequestBody TbCustLinkman entity) {
        entityService.updateById(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @DeleteMapping("delete/{id}")
    @PreAuthorize("hasAuthority('user:linkman:delete')")
    public ResponseEntity<ApiModel> delete(@PathVariable("id") String id) {
        entityService.removeById(id);
        return ResponseEntity.ok(ApiModel.ok());
    }



    @RequestMapping("listByCustomerId")
    public ResponseEntity<ApiModel> listByCustomerId(String custId) {
        //如果ID值是空的
        if(StringUtils.isEmpty(custId)){
            return ResponseEntity.ok(ApiModel.ok());
        }
        //根据企业id查询联系人
        List<TbCustLinkman> list =
                entityService.
                lambdaQuery()
                .eq(TbCustLinkman::getCustId, custId)
                .list();


        return ResponseEntity.ok(ApiModel.data(list));
    }

    @RequestMapping("/export")
    public void export(HttpServletResponse response)
            throws UnsupportedEncodingException {
        //1. 准备你需要导出的数据
        List<TbCustLinkman> tbCustLinkmenList = entityService.list();


        //设置属性
        ExportParams exportParams=new ExportParams();
        //2. 封装成workbook
        /**
         * 参数一: 表格属性
         * 参数二: 你需要导出的实体类的字节码  需要配合@Excel注释使用
         * 参数三: 你需要导出的数据
         */
        Workbook workbook = ExcelExportUtil.exportExcel
                (exportParams,
                 TbCustLinkman.class,
                        tbCustLinkmenList);
        //3. 导出
        /**
         * 参数一 需要一个响应
         * 参数二 文件名字
         * 参数三 工作簿
         */
        PoiExportHelper.exportExcel(response,"客户联系人管理",workbook);
    }
    /** ---------------------------**/

    @GetMapping("import.html")
    public ModelAndView toImport(ModelAndView mv) {

        mv.setViewName("user/linkman/importUser");
        return mv;
    }

    @GetMapping("template")
    public void template(HttpServletResponse response) throws UnsupportedEncodingException {
        ExcelExportEntityWrapper wrapper = new ExcelExportEntityWrapper();
        wrapper.entity(TbCustLinkman.LINKMAN_COL,"linkman",30);


        Workbook workbook = ExcelExportUtil.exportExcel(
                new ExportParams(),
                wrapper.getResult(),
                new ArrayList<>());

        PoiExportHelper.exportExcel(response, "客户联系人管理", workbook);

    }


    @PostMapping("import")
    public ResponseEntity importUser(MultipartFile file) throws Exception {
        //上传的参数
        ImportParams params = PoiImportHelper.buildImportParams(
                new String[]{
                        TbCustLinkman.LINKMAN_COL,
                }, new Class[]{ImportGroup.class});


        //上传的结果集
        List<TbCustLinkman> custLinkmanList = ExcelImportUtil.importExcel(
                file.getInputStream(),
                TbCustLinkman.class, params);

        //批量保存
        entityService.saveBatch(custLinkmanList);



        return ResponseEntity.ok(ApiModel.ok());
    }


}
